<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="customer-list-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户名称"
            clearable
            style="width: 200px;"
          />
        </el-form-item>

        <el-form-item label="客户类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择客户类型"
            clearable
            style="width: 180px;"
          >
            <el-option label="个人客户" value="0" />
            <el-option label="企业客户" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="客户状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择客户状态"
            clearable
            style="width: 180px;"
          >
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增客户
        </el-button>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card class="list-card">
      <el-table
        :data="customerList"
        border
        stripe
        v-loading="loading"
        element-loading-text="加载中..."
        style="width: 100%;"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />

        <el-table-column prop="customerName" label="客户名称" min-width="120">
          <template #default="scope">
            <span class="customer-name">{{ scope.row.customerName }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="phone" label="联系电话" min-width="120" />

        <el-table-column prop="type" label="客户类型" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.type === '0' ? 'info' : 'success'">
              {{ scope.row.type === '0' ? '个人客户' : '企业客户' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="address" label="地址" min-width="150">
          <template #default="scope">
            <el-tooltip :content="scope.row.address || '无地址'">
              <div class="ellipsis">{{ scope.row.address || '无地址' }}</div>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="updateTime" label="最后更新" min-width="160">
          <template #default="scope">
            {{ formatTime(scope.row.updateTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="200" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.pageNo"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pagination.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-if="!loading && total === 0 && customerList.length === 0">
        <el-empty
          image="empty"
          description="暂无客户数据"
        >
          <el-button type="primary" @click="handleAdd">新增客户</el-button>
        </el-empty>
      </div>
    </el-card>

    <!-- 客户表单弹窗 (新增/编辑) -->
    <CustomerForm
      v-model:visible="formVisible"
      :model-value="currentCustomer"
      @save="handleSave"
    />

    <!-- 客户详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="客户详情"
      :width="600"
      :close-on-click-modal="false"
    >
      <el-descriptions column="1" border class="detail-info">
        <el-descriptions-item label="客户名称">{{ currentCustomer.customerName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentCustomer.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="客户类型">
          {{ currentCustomer.type === '0' ? '个人客户' : currentCustomer.type === '1' ? '企业客户' : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="联系地址">{{ currentCustomer.address || '无地址' }}</el-descriptions-item>
        <el-descriptions-item label="客户状态">
          {{ currentCustomer.status === 1 ? '正常' : currentCustomer.status === 0 ? '禁用' : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatTime(currentCustomer.createTime) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="最后更新时间">{{ formatTime(currentCustomer.updateTime) || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox, ElEmpty } from 'element-plus';
import { reactive, ref, onMounted } from 'vue';
import { getCustomers, deleteCustomer, updateCustomer, createCustomer,searchCustomersByName } from '@/api/customer';
import { Plus } from '@element-plus/icons-vue';
import CustomerForm from './components/create.vue';

// 修复核心问题：初始化客户列表为空数组，确保响应式正确
const customerList = ref([]);
const loading = ref(false);
const total = ref(0);

// 搜索表单
const searchForm = reactive({
  customerName: '',
  type: '',
  status: ''
});

// 分页参数
const pagination = reactive({
  pageNo: 1,
  pageSize: 10
});

// 弹窗控制
const formVisible = ref(false);
const detailVisible = ref(false);
const currentCustomer = ref({});

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  try {
    const date = new Date(time);
    return date.toLocaleString();
  } catch (error) {
    console.error('时间格式化失败:', error);
    return time;
  }
};

// 获取客户列表
const fetchCustomerList = async () => {
  try {
    loading.value = true;
    const params = {
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      customerName: searchForm.customerName || undefined,
      type: searchForm.type || undefined,
      status: searchForm.status ? Number(searchForm.status) : undefined
    };

    let response;
    if (searchForm.customerName) {
      response = await searchCustomersByName(params);
    } else {
      response = await getCustomers(params);
    }

    // 验证基础响应结构
    if (!response || typeof response !== 'object') {
      throw new Error('接口返回格式不正确（不是有效的JSON对象）');
    }

    // 验证状态码（根据实际返回，0表示成功）
    if (response.code !== 0) {
      throw new Error(`接口调用失败: ${response.msg || '未知错误'}`);
    }

    // 验证数据结构
    if (!response.data || !Array.isArray(response.data.records)) {
      throw new Error('接口返回数据格式不正确（缺少记录列表）');
    }

    // 正确解析数据
    customerList.value = response.data.records;
    total.value = Number(response.data.total) || 0;

    // 更新分页信息
    pagination.current = response.data.current || 1;
    pagination.pageSize = response.data.size || 10;

  } catch (error) {
    console.error('获取客户列表失败:', error);
    ElMessage.error('获取客户列表失败: ' + (error.message || '未知错误'));
    customerList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};
// 搜索与重置
const handleSearch = () => {
  pagination.pageNo = 1;
  fetchCustomerList();
};

const resetSearch = () => {
  searchForm.customerName = '';
  searchForm.type = '';
  searchForm.status = '';
  pagination.pageNo = 1;
  fetchCustomerList();
};

// 分页事件
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.pageNo = 1;
  fetchCustomerList();
};

const handleCurrentChange = (page) => {
  pagination.pageNo = page;
  fetchCustomerList();
};

// 新增客户
const handleAdd = () => {
  currentCustomer.value = {};
  formVisible.value = true;
};

// 编辑客户
const handleEdit = (row) => {
  currentCustomer.value = { ...row };
  formVisible.value = true;
};

// 查看客户详情
const handleView = (row) => {
  currentCustomer.value = { ...row };
  detailVisible.value = true;
};

// 删除客户
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该客户吗？', '删除确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await deleteCustomer(id);
    // 根据实际接口返回调整判断条件
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('删除成功');
      fetchCustomerList();
    } else {
      ElMessage.error('删除失败: ' + (res.msg || '未知错误'));
    }
  } catch (error) {
    if (error === 'cancel') return;
    ElMessage.error('删除失败: ' + (error.message || '操作被中断'));
    console.error(error);
  }
};

// 保存客户（新增或编辑）
const handleSave = async (formData) => {
  try {
    loading.value = true;

    if (formData.id) {
      // 编辑操作
      const formattedData = {
        ...formData,
        type: formData.type === 'individual' ? '0' : '1',
        status: formData.status ? 1 : 0,
        customerName: formData.name
      };
      await updateCustomer(formattedData);
    } else {
      // 新增操作
      const formattedData = {
        customerName: formData.name,
        phone: formData.phone,
        type: formData.type === 'individual' ? '0' : '1',
        address: formData.address,
        status: formData.status ? 1 : 0
      };
      const response = await createCustomer(formattedData);
      if (response.data) {
        ElMessage.success(`新增成功，客户ID: ${response.data.id}`);
      }
    }

    ElMessage.success(formData.id ? '编辑成功' : '新增成功');
    formVisible.value = false;
    fetchCustomerList(); // 重新加载列表
  } catch (error) {
    ElMessage.error(`${formData.id ? '编辑' : '新增'}失败: ${error.message || '未知错误'}`);
    console.error(error);
  } finally {
    loading.value = false;
  }
};



// 页面加载时获取数据
onMounted(() => {
  fetchCustomerList();
});
</script>

<style scoped>
.customer-list-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.list-card {
  background-color: #fff;
}

.customer-name {
  font-weight: 500;
  color: #1890ff;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.empty-state {
  padding: 50px 0;
  text-align: center;
}

.detail-info {
  margin-top: 10px;
}
</style>
